// pages/cart/index.js

import {
    getSetting,
    chooseAddress,
    openSetting,
    showModal,
    showToast
} from "../../utils/asyncWx.js"

Page({
    data: {
        address: {},
        cart: [],
        allChecked: false,
        totalPrice: 0,
        totalNum: 0

    },
    onShow() {
        const address = wx.getStorageSync('address');
        const cart = wx.getStorageSync('cart') || [];
        this.setData({
            address
        })
        this.setCart(cart);
    },

    async handleChooseAddress() {
        try {
            const res1 = await getSetting();
            const scopeAddress = res1.authSetting["scope.address"];
            if (scopeAddress === false) {
                await openSetting();
            }
            const res2 = await chooseAddress();
            wx.setStorageSync('address', res2)

            //优化1
            // if(scopeAddress === true || scopeAddress === undefined){
            //     const res2 = await chooseAddress();
            //     console.log(res2);
            // }else{
            //     const res3 = await openSetting();
            //     const res4 = await chooseAddress();
            //     console.log(res4);
            // }

            //原始代码
            //1.获取权限状态  authSetting scope.address
            // wx.getSetting({
            //     success: (result) => {
            //         const scopeAddress = result.authSetting["scope.address"];
            //         if(scopeAddress === true || scopeAddress === undefined){
            //             wx.chooseAddress({
            //                 success: (result1)=>{
            //                     console.log(result1);
            //                 }, 
            //             });
            //         }else{
            //             wx.openSetting({
            //                 success: (result2)=>{
            //                     wx.chooseAddress({
            //                         success: (result3)=>{
            //                             console.log(result3);
            //                         },

            //                     });
            //                 },
            //             });
            //         }
            //     },
            // });
        } catch (error) {
            console.log(error);
        }
    },

    handeItemChange(e) {
        //获取被修改商品的ID
        const goods_id = e.currentTarget.dataset.id;
        //获取购物车数组
        let {
            cart
        } = this.data;
        //找到被修改的商品对象
        let index = cart.findIndex(v => v.data.message.goods_id === goods_id);
        //选中状态取反
        cart[index].checked = !cart[index].checked

        this.setCart(cart)
    },

    //设置购物车状态 同时重新计算 底部工具栏的数据 全选
    setCart(cart) {
        let allChecked = true;
        let totalPrice = 0;
        let totalNum = 0;
        cart.forEach(v => {
            if (v.checked) {
                totalPrice += v.num * v.data.message.goods_price;
                totalNum += v.num;
            } else {
                allChecked = false;
            }
        })
        //判断购物车数组是否为空  
        allChecked = cart.length != 0 ? allChecked : false;
        this.setData({
            cart,
            allChecked,
            totalPrice,
            totalNum
        });
        wx.setStorageSync('cart', cart);
    },

    //商品全选功能
    handleItemAllChecked() {
        let {cart,allChecked
        } = this.data;
        allChecked = !allChecked;
        cart.forEach(v => v.checked = allChecked);
        this.setCart(cart);
    },
    //商品数量的加减编辑
    async handleItemNumEdit(e) {
        const {operation,id} = e.currentTarget.dataset;
        let {cart} = this.data;
        const index = cart.findIndex(v => v.data.message.goods_id === id);

        if (cart[index].num === 1 && operation===-1) {
            const res = await showModal({content:"您是否要删除？"})
            if (res.confirm) {
                cart.splice(index, 1);
                this.setCart(cart);
            }
        } else {
            cart[index].num += operation;
            this.setCart(cart);
        }

    },
    async Settlement(){
        const {address,cart} = this.data;
        if(!address.userName){
            await showToast({title:"您还没有设置收货地址"});
            return;
        }
        if(cart.length === 0){
            await showToast({title:"您还没有添加商品"});
            return;
        }
        wx.navigateTo({
            url: '/pages/pay/index',
        })
        //判断用户有没有选中商品

    }
})